package burp;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by shuaidong on 2017/6/24.
 */
public class SnifferContextMenuFactory implements IContextMenuFactory {
    private IExtensionHelpers helpers;
    private PrintWriter stdout;

    public SnifferContextMenuFactory(IExtensionHelpers helpers,PrintWriter stdout) {
        this.helpers = helpers;
        this.stdout =  stdout;
    }

    public List<JMenuItem> createMenuItems(final IContextMenuInvocation invocation) {
        List<JMenuItem> jMenuItemList = new ArrayList<JMenuItem>();

        JMenuItem jMenuItem = new JMenuItem("send to sqlmap");
        jMenuItemList.add(jMenuItem);

        jMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
               IHttpRequestResponse[] messages = invocation.getSelectedMessages();
           //    stdout.println(new String(messages[0].getRequest()));

               int length = messages.length;

               BufferedWriter filewrite = null;

               List<String> tmpfilename = Context.getTmpFilenameTmp(true,length);
                stdout.println(tmpfilename.get(0));
                for (int i=0;i<length;i++){
                    try {
                        stdout.println(tmpfilename.get(i));

                       File file =  new File(tmpfilename.get(i));
                       if (!file.exists()){
                           File fileParent = file.getParentFile();
                           if (!fileParent.exists()){
                               fileParent.mkdirs();
                           }
                           file.createNewFile();
                       }
                        stdout.println(new String(messages[i].getRequest()));
                        filewrite = new BufferedWriter(new FileWriter(file));
                        filewrite.write(new String(messages[i].getRequest()));
                        filewrite.flush();
                        filewrite.close();



                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }

                new Thread(new SqlmapStart(stdout)).start();

            }
        });


        return jMenuItemList;
    }






}
